package com.team9.interceptor;


import com.google.gson.Gson;
import com.team9.annotation.JwtAnno;
import com.team9.dto.ActionResult;
import com.team9.util.JwtUtil;


import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;


/**
 * 业务访问时拦截器
 *
 * @author YoungKai
 * @date 2021/1/7 14:01
 */
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {

    /**
     * 事前（进入接口方法前）处理
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURI = request.getRequestURI();
        log.info("------------------"+requestURI);
        String token = request.getHeader("token");
        log.info("------------------"+token);

        if (handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod)handler;
            //获取拦截的方法
            Method method  = hm.getMethod();
            JwtAnno jwtAnno = method.getAnnotation(JwtAnno.class);

            if (jwtAnno != null){
                //方法前含有指定注解，需要验证token
                boolean checkToken = JwtUtil.checkToken(token);
                log.info("==============="+token+":"+checkToken);
                if (checkToken){
                    return true;
                }else{
                    ActionResult actionResult = new ActionResult(403,"token invidite",null);
                    String json = new Gson().toJson(actionResult);
                    PrintWriter out = response.getWriter();
                    response.setHeader("contentType","application/json ");
                    out.write(json);
                    return  false;
                }
            }else{
                //无需拦截的处理方法
                return true;
            }
        }else{
            return true;
        }
    }
    /**
        事后（执行完接口逻辑，未进入视图解析器前）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 解析完返回视图
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
